﻿using UnityEngine;
using System.Collections;
using KingSley;
using UnityEngine.AI;

public class PlayerMouseTouch : MonoSingleton<PlayerMouseTouch>
{
    private float playerToPointDistance;
    private bool isMove;
    public Vector3 vtTargetPos;
    private NavMeshAgent playerNavAgent;

    private void Start()
    {
        isMove = false;
        vtTargetPos = Vector3.zero;
        playerNavAgent = GetComponent<NavMeshAgent>();
    }

    private void Update()
    {
        if (PlayerAttributeControl.Instance().CurStatus.CurHP > 0) 
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit))
            {
                if (hit.collider.tag == "Ground")
                {
                    playerToPointDistance = Vector3.Distance(transform.position, hit.point);
                    if (Input.GetMouseButtonDown(1))
                    {
                        isMove = true;
                        vtTargetPos = hit.point;
                    }
                }
            }
            if (isMove)
            {
                transform.LookAt(vtTargetPos);
                if (vtTargetPos.z > 4.5f) vtTargetPos.z = 4.5f;
                if (vtTargetPos.z < -23f) vtTargetPos.z = -23f;
                if (vtTargetPos.x > 22f) vtTargetPos.x = 22f;
                if (vtTargetPos.x < -16f) vtTargetPos.x = -16f;
                PlayerAnimatorController.Instance().PlayerWalk();
                playerNavAgent.speed = PlayerAttributeControl.Instance().CurStatus.CurMoveSpeed;
                playerNavAgent.SetDestination(vtTargetPos);
                playerToPointDistance = Vector3.Distance(transform.position, vtTargetPos);
                if (playerToPointDistance > 3f)
                {
                    playerNavAgent.speed = PlayerAttributeControl.Instance().CurStatus.CurRotationSpeed;
                    PlayerAnimatorController.Instance().PlayerRun();
                }
                else if (playerToPointDistance <= 2f && playerToPointDistance > 0.5f)
                {
                    playerNavAgent.speed = PlayerAttributeControl.Instance().CurStatus.CurMoveSpeed;
                    PlayerAnimatorController.Instance().PlayerWalk();
                }
                else if (playerToPointDistance <= 0.5f)
                {
                    PlayerAnimatorController.Instance().PlayerIdle();
                    isMove = false;
                }
            }
        }
    }
}
